import { createRouter, createWebHistory } from 'vue-router'
import { get } from '@/utils/service.ts'
import {
  TEST_STATE,
  VUE_APP_BASE_API,
  SESSION_LAST_CODE,
  SESSION_MEMBER_INFO,
} from '@/utils/baseConfig'
import { showDialog } from 'vant'
const baseWebROOT = '/wechat/'
const router = createRouter({
  history: createWebHistory(baseWebROOT),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/HomeView.vue'),
      meta: {
        requiresAuth: true,
        inState: true, //是否为入口页面 入口页面必须带code参数
      },
    },
    { path: '/log', name: 'log', component: () => import('../views/LoginIn.vue') },
    {
      path: '/rewards',
      name: 'rewards',
      component: () => import('../views/news/reward/RewardList.vue'),
    },
    {
      path: '/newList',
      name: 'newList',
      component: () => import('../views/news/new/NewList.vue'),
    },
    {
      path: '/rewardDetail',
      name: 'rewardDetail',
      component: () => import('../views/news/reward/RewardDetail.vue'),
    },
    {
      path: '/newDetail',
      name: 'newDetail',
      component: () => import('../views/news/new/NewDetail.vue'),
    },
    {
      path: '/bussiHandCarImages',
      name: 'bussiHandCarImages',
      component: () => import('../views/news/handCarImage/BussiHandCarImage.vue'),
    },
    {
      path: '/activityList',
      name: 'actvityList',
      component: () => import('../views/news/activity/ActivityList.vue'),
    },
    {
      path: '/activityDetail',
      name: 'activityDetail',
      component: () => import('../views/news/activity/ActivityDetail.vue'),
    },
    {
      path: '/recommendCustomer', //推荐客户需要会员权限
      name: 'recommendCustomer',
      component: () => import('../views/recommend/recommendCustomer.vue'),
      meta: {
        requiresAuth: true, // 判断是否需要登录
        memberAuth: true, // 判断是否需要会员权限
      },
    },
    {
      path: '/memberReg',
      name: 'memberReg',
      component: () => import('../views/member/memberReg.vue'),
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/my', // 我的中心页面需要会员权限
      name: 'myCent',
      component: () => import('../views/MyCent.vue'),
      meta: {
        requiresAuth: true,
        memberAuth: true,
        inState: true,
      },
    },
    {
      path: '/myPoint',
      name: 'myPoint',
      component: () => import('../views/my/my/MyPoint.vue'),
    },
    {
      path: '/myCoupon',
      name: 'myCoupon',
      component: () => import('../views/my/my/MyCoupon.vue'),
    },
    {
      path: '/memberCard',
      name: 'memberCard',
      component: () => import('../views/my/my/MemberCard.vue'),
    },
    {
      path: '/myOnline',
      name: 'myOnline',
      component: () => import('../views/my/my/MyOnline.vue'),
    },
    {
      path: '/myReward',
      name: 'myReward',
      component: () => import('../views/my/agent/MyReward.vue'),
    },
    {
      path: '/myRecommendCustomer',
      name: 'myRecommendCustomer',
      component: () => import('../views/my/agent/MyRecommendCustomer.vue'),
    },
    {
      path: '/myRecommendCustomerDetail',
      name: 'myRecommendCustomerDetail',
      component: () => import('../views/my/agent/MyRecommendCustomerDetail.vue'),
    },
    {
      path: '/myChildreen',
      name: 'myChildreen',
      component: () => import('../views/my/agent/MyChildreen.vue'),
    },
    {
      path: '/carMasterAuth',
      name: 'carMasterAuth',
      component: () => import('../views/my/agent/CarMasterAuth.vue'),
    },
    {
      path: '/mySpreadQrCode',
      name: 'mySpreadQrCode',
      component: () => import('../views/my/agent/MySpreadQrCode.vue'),
    },
    {
      path: '/carMasterInfo',
      name: 'carMasterInfo',
      component: () => import('../views/my/carMaster/CarMasterInfo.vue'),
    },
    {
      path: '/memberInfo',
      name: 'memberInfo',
      component: () => import('../views/my/carMaster/MemberInfo.vue'),
    },
    {
      path: '/changeMobilePhone',
      name: 'changeMobilePhone',
      component: () => import('../views/my/carMaster/ChangeMobilePhone.vue'),
    },
    {
      path: '/myReception',
      name: 'myReception',
      component: () => import('../views/my/carMaster/MyReception.vue'),
    },
    {
      path: '/tryCar',
      name: 'tryCar',
      component: () => import('../views/online/TryCar.vue'),
      meta: {
        inState: true,
      },
    },
    {
      path: '/oldCarChange',
      name: 'oldCarChange',
      component: () => import('../views/online/OldCarChange.vue'),
      meta: {
        inState: true,
      },
    },
    {
      path: '/examined',
      name: 'examined',
      component: () => import('../views/online/Examined.vue'),
      meta: {
        inState: true,
      },
    },
    {
      path: '/bookingRepair',
      name: 'bookingRepair',
      component: () => import('../views/online/BookingRepair.vue'),
      meta: {
        inState: true,
      },
    },
    {
      path: '/rewardRole',
      name: 'rewardRole',
      component: () => import('../views/news/reward/RewardRole.vue'),
    },
  ],
})
// 可选的全局前置路由守卫，用于处理认证
router.beforeEach((to, from, next) => {
  if (to.meta.inState != undefined && to.meta.inState == true) {
    //入口页面获取code参数，并更新参数
    const code = to.query.code || ''
    if (code != '' && code != null && code != undefined) {
      localStorage.setItem(SESSION_LAST_CODE, code)
    }
  }
  if (!to.meta.requiresAuth) {
    //不需获取用户openId
    next()
  } else {
    const code = localStorage.getItem(SESSION_LAST_CODE) //获取微信code
    console.log('code：' + code)
    //需要会员登录权限
    const memberInfoStr = localStorage.getItem(SESSION_MEMBER_INFO + code) || ''
    let memberInfo = {}
    if (isJSON(memberInfoStr)) {
      memberInfo = JSON.parse(memberInfoStr)
    } else {
      memberInfo = {}
    }
    if (memberInfo.openId == undefined) {
      if (TEST_STATE == 'test') {
        const memberInfo = getMemberInfo(code)
        localStorage.setItem(SESSION_MEMBER_INFO + code, JSON.stringify(memberInfo))
        next()
      } else if (TEST_STATE == 'online') {
        get('/weixinAccountWechatNew/queryWechatByCode', {
          code: code,
        })
          .then((res) => {
            console.log(res)
            if (res.code == 0) {
              const weixinAccount = res.data
              // 触发微信授权流程，详见后续部分
              if (weixinAccount != undefined) {
                const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${weixinAccount.appId}&redirect_uri=${encodeURIComponent(
                  '' + VUE_APP_BASE_API + '/wechat/log?scope=snsapi_userinfo',
                )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
                window.location.href = url
              }
            } else {
              showDialog({
                message: '未获取到微信公众号商户信息，请退出联系管理员',
              }).then(() => {
                // on close
              })
            }
          })
          .catch((err) => {
            if (isJSON(err)) {
            } else {
            }
            console.log(err)
          })
      }
    } else {
      //
      console.log(to.fullPath)
      console.log(to.meta.memberAuth)
      if (undefined != to.meta.memberAuth && to.meta.memberAuth) {
        //需要会员认证
        if (memberInfo.memAuthStatus == 1) {
          to.fullPath.replace('/', '')
          router.push({
            path: '/memberReg',
            query: { redirect: baseWebROOT + replaceUrl(to.fullPath) },
          }) //会员注册页面
        } else {
          next()
        }
      } else {
        next()
      }
    }
  }
})
function getMemberInfo(code) {
  if (code == '36c32f92fe5458abe53ce7b908031073') {
    const obj = {
      openId: 'oVdlDxNEHpbJ4Xh4R3M29C0eMhFw',
      dbid: 3194,
      memberNo: 'M20250626307222',
      nickName: '舒三战',
      name: '三战',
      mobilePHone: '18708150883',
      memAuthStatus: 2,
      memberShipLevelName: '普通会员',
    }
    return obj
  } else {
    const obj = {
      openId: 'oVdlDxAZKEjLjQmJ3QJX3CUGji34',
      dbid: 2158,
      memberNo: '20180202431037',
      nickName: '吴洪伟',
      name: '吴洪伟',
      mobilePHone: '18655300061',
      memAuthStatus: 2,
      memberShipLevelName: '普通会员',
    }
    return obj
  }
}
function replaceUrl(url: string) {
  const index = url.indexOf('/')
  if (index == 0) {
    url = url.substring(index + 1, url.length)
  }
  return url
}
function isJSON(data) {
  try {
    const obj = JSON.parse(data)
    if (typeof obj === 'object') {
      console.log('数据是JSON格式')
      console.log(obj)
      return true
    } else {
      console.log('数据是字符串格式')
      console.log(data)
      return false
    }
  } catch (e) {
    console.log('数据是字符串格式')
    console.log(data)
    return false
  }
}
export default router
